import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

// CameraPage 现在是一个可以直接 push 到 Navigator 的页面
class CameraPage extends StatelessWidget {
  const CameraPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Picker 示例'),
      ),
      body: ImagePickerContent(),
    );
  }
}

// 提取核心内容为一个 StatefulWidget，便于复用和状态管理
class ImagePickerContent extends StatefulWidget {
  @override
  _ImagePickerContentState createState() => _ImagePickerContentState();
}

class _ImagePickerContentState extends State<ImagePickerContent> {
  XFile? _image;

  Future<void> _pickImage(ImageSource source) async {
    final picker = ImagePicker();
    final XFile? pickedFile = await picker.pickImage(
      source: source,
      imageQuality: 50, // 调整图片质量（0-100）
    );

    if (pickedFile != null) {
      setState(() {
        _image = pickedFile;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (_image != null) Image.file(File(_image!.path)), // 显示选中的图片
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: () => _pickImage(ImageSource.camera),
            child: const Text('拍照'),
          ),
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () => _pickImage(ImageSource.gallery),
            child: const Text('从相册选择'),
          ),
        ],
      ),
    );
  }
}
